import { View, Text, ScrollView, Image, TouchableOpacity, Alert } from 'react-native';
import { useState, useRef } from 'react';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import { Swipeable } from 'react-native-gesture-handler';

// 模拟购物车数据
const cartData = [
  {
    id: '1',
    title: '大咖喵咪手办',
    price: 199,
    originPrice: 299,
    image: require('../../assets/product/p1.jpg'),
    quantity: 1,
    selected: true,
  },
  {
    id: '2',
    title: '大咖龙舞手办',
    price: 299,
    originPrice: 399,
    image: require('../../assets/product/p2.jpg'),
    quantity: 2,
    selected: true,
  },
  {
    id: '3',
    title: '欧珑赤霞橘光护手霜柑橘果香调滋润补水情人节推荐女',
    price: 159,
    originPrice: 199,
    image: require('../../assets/product/p3.png'),
    quantity: 1,
    selected: true,
  }
];

// 添加推荐商品数据
const recommendProducts = [
  {
    id: '1',
    title: '大咖喵咪手办',
    price: 199,
    image: require('../../assets/product/p1.jpg'),
  },
  {
    id: '2',
    title: '大咖龙舞手办',
    price: 299,
    image: require('../../assets/product/p2.jpg'),
  },
  {
    id: '3',
    title: '欧珑赤霞橘光护手霜柑橘果香调滋润补水情人节推荐女',
    price: 159,
    image: require('../../assets/product/p3.png'),
  },
  {
    id: '4',
    title: 'freres法国植物学家CF香薰蜡烛小番茄',
    price: 129,
    image: require('../../assets/product/p4.png'),
  },
];

export default function CartPage() {
  const insets = useSafeAreaInsets();
  const [cart, setCart] = useState(cartData);
  const [allSelected, setAllSelected] = useState(true);
  const [isManage, setIsManage] = useState(false);
  
  // 存储所有 Swipeable 引用
  const swipeableRefs = useRef<{ [key: string]: Swipeable | null }>({});

  // 计算总价
  const totalPrice = cart
    .filter(item => item.selected)
    .reduce((sum, item) => sum + item.price * item.quantity, 0);

  // 计算总数量
  const totalQuantity = cart
    .filter(item => item.selected)
    .reduce((sum, item) => sum + item.quantity, 0);

  // 更新商品数量
  const updateQuantity = (id: string, delta: number) => {
    setCart(prev => prev.map(item => {
      if (item.id === id) {
        const newQuantity = Math.max(1, item.quantity + delta);
        return { ...item, quantity: newQuantity };
      }
      return item;
    }));
  };

  // 切换商品选中状态
  const toggleSelect = (id: string) => {
    setCart(prev => {
      const newCart = prev.map(item => 
        item.id === id ? { ...item, selected: !item.selected } : item
      );
      setAllSelected(newCart.every(item => item.selected));
      return newCart;
    });
  };

  // 切换全选状态
  const toggleSelectAll = () => {
    const newSelected = !allSelected;
    setAllSelected(newSelected);
    setCart(prev => prev.map(item => ({ ...item, selected: newSelected })));
  };

  // 删除商品
  const handleDelete = (id: string) => {
    Alert.alert(
      '确认删除',
      '是否确认将该商品从购物车中删除？',
      [
        {
          text: '取消',
          style: 'cancel',
          onPress: () => {
            // 关闭滑动状态
            swipeableRefs.current[id]?.close();
          }
        },
        {
          text: '删除',
          style: 'destructive',
          onPress: () => {
            setCart(prev => prev.filter(item => item.id !== id));
          }
        }
      ]
    );
  };

  // 渲染滑动删除按钮
  const renderRightActions = (id: string) => {
    return (
      <View className="flex-row">
        <TouchableOpacity
          className="bg-red-500 w-16 h-full items-center justify-center"
          onPress={() => handleDelete(id)}
          activeOpacity={0.7}
        >
          <Ionicons name="trash-outline" size={20} color="white" />
          <Text className="text-white text-xs mt-1">删除</Text>
        </TouchableOpacity>
      </View>
    );
  };

  return (
    <View 
      className="flex-1 bg-gray-100"
      // style={{ paddingTop: insets.top }}
    >
      {/* 顶部标题栏 */}
      <View className="px-4 h-12 flex-row items-center justify-between bg-white shadow-sm">
        <View className="flex-row items-center">
          <Text className="text-lg font-semibold text-gray-800">购物车</Text>
          <Text className="ml-2 text-sm text-gray-400">
            ({cart.length}件商品)
          </Text>
        </View>
        <TouchableOpacity 
          className="h-8 px-3 flex-row items-center rounded-full bg-gray-50"
          activeOpacity={0.6}
          onPress={() => setIsManage(!isManage)}
        >
          <Ionicons 
            name={isManage ? "create" : "create-outline"} 
            size={16} 
            color="#666"
          />
          <Text className="ml-1 text-sm text-gray-600">
            {isManage ? '完成' : '管理'}
          </Text>
        </TouchableOpacity>
      </View>

      {cart.length > 0 ? (
        <ScrollView className="flex-1" showsVerticalScrollIndicator={false}>
          {/* 购物车列表 */}
          <View className="mt-2 px-3">
            {cart.map(item => (
              <Swipeable
                key={item.id}
                ref={ref => swipeableRefs.current[item.id] = ref}
                renderRightActions={() => renderRightActions(item.id)}
                overshootRight={false}
                containerStyle={{ marginBottom: 10 }}
              >
                <View 
                  className="bg-white rounded-xl shadow-sm overflow-hidden"
                >
                  <View className="px-2 py-1 flex-row items-center">
                    <TouchableOpacity
                      activeOpacity={0.6}
                      onPress={() => toggleSelect(item.id)}
                      className="mr-3 w-5 h-5"
                    >
                      <Ionicons
                        name={item.selected ? "checkmark-circle" : "ellipse-outline"}
                        size={20}
                        color={item.selected ? "#f43f5e" : "#d1d5db"}
                      />
                    </TouchableOpacity>
                    
                    <Image
                      source={item.image}
                      className="w-20 h-20 rounded-lg"
                      resizeMode="cover"
                    />
                    
                    <View className="flex-1 ml-3 h-22 justify-between">
                      <View>
                        <Text 
                          numberOfLines={2}
                          className="text-sm text-gray-700 leading-5"
                        >
                          {item.title}
                        </Text>
                        
                        <View className="flex-row items-baseline mt-1">
                          <Text className="text-red-500 font-medium">¥</Text>
                          <Text className="text-red-500 text-lg font-semibold">
                            {item.price}
                          </Text>
                          <Text className="text-xs text-gray-400 line-through ml-1">
                            ¥{item.originPrice}
                          </Text>
                        </View>
                      </View>

                      <View className="flex-row items-center justify-end mb-2">
                        <View className="flex-row items-center bg-gray-50 rounded-full overflow-hidden">
                          <TouchableOpacity
                            className="w-7 h-7 items-center justify-center"
                            onPress={() => updateQuantity(item.id, -1)}
                            activeOpacity={0.6}
                          >
                            <Ionicons name="remove" size={16} color="#666" />
                          </TouchableOpacity>
                          
                          <Text className="min-w-[32px] text-center text-sm">
                            {item.quantity}
                          </Text>
                          
                          <TouchableOpacity
                            className="w-7 h-7 items-center justify-center"
                            onPress={() => updateQuantity(item.id, 1)}
                            activeOpacity={0.6}
                          >
                            <Ionicons name="add" size={16} color="#666" />
                          </TouchableOpacity>
                        </View>
                      </View>
                    </View>
                  </View>
                </View>
              </Swipeable>
            ))}
          </View>

          {/* 底部推荐 */}
          <View className="mt-2 mb-4 px-3">
            <View className="flex-row items-center justify-between mb-3">
              <View className="flex-row items-center">
                <Ionicons name="heart" size={18} color="#f43f5e" />
                <Text className="text-base font-medium text-gray-800 ml-1">猜你喜欢</Text>
              </View>
              <TouchableOpacity 
                className="flex-row items-center"
                activeOpacity={0.6}
              >
                <Text className="text-sm text-gray-400 mr-1">查看更多</Text>
                <Ionicons name="chevron-forward" size={14} color="#9ca3af" />
              </TouchableOpacity>
            </View>
            <ScrollView 
              horizontal 
              showsHorizontalScrollIndicator={false}
              className="flex-row"
            >
              {recommendProducts.map(item => (
                <TouchableOpacity
                  key={item.id}
                  className="mr-3 w-32"
                  activeOpacity={0.7}
                >
                  <View className="w-32 h-32 bg-white rounded-lg mb-2 overflow-hidden shadow-sm">
                    <Image 
                      source={item.image}
                      className="w-full h-full"
                      resizeMode="cover"
                    />
                  </View>
                  <Text 
                    className="text-sm text-gray-700 leading-5" 
                    numberOfLines={2}
                  >
                    {item.title}
                  </Text>
                  <View className="flex-row items-baseline mt-1">
                    <Text className="text-red-500 text-xs font-medium">¥</Text>
                    <Text className="text-red-500 text-base font-semibold">
                      {item.price}
                    </Text>
                  </View>
                </TouchableOpacity>
              ))}
            </ScrollView>
          </View>
        </ScrollView>
      ) : (
        <View className="flex-1 items-center justify-center">
          <Ionicons name="cart-outline" size={64} color="#d1d5db" />
          <Text className="mt-4 text-gray-400">购物车还是空的</Text>
          <TouchableOpacity
            className="mt-4 px-6 py-2 bg-red-500 rounded-full"
            activeOpacity={0.7}
          >
            <Text className="text-white font-medium">去逛逛</Text>
          </TouchableOpacity>
        </View>
      )}

      {/* 底部结算栏 */}
      {cart.length > 0 && (
        <View 
          className="bg-white px-4 py-2 flex-row items-center justify-between shadow-lg"
          style={{ paddingBottom: insets.bottom || 16 }}
        >
          <View className="flex-row items-center">
            <TouchableOpacity
              activeOpacity={0.6}
              onPress={toggleSelectAll}
              className="flex-row items-center"
            >
              <Ionicons
                name={allSelected ? "checkmark-circle" : "ellipse-outline"}
                size={20}
                color={allSelected ? "#f43f5e" : "#d1d5db"}
              />
              <Text className="ml-2 text-sm text-gray-600">全选</Text>
            </TouchableOpacity>
            
            <View className="ml-4">
              <Text className="text-sm text-gray-600">
                合计: 
                <Text className="text-red-500 font-medium"> ¥</Text>
                <Text className="text-red-500 text-xl font-semibold">{totalPrice}</Text>
              </Text>
              <Text className="text-xs text-gray-400">
                已选{totalQuantity}件商品
              </Text>
            </View>
          </View>

          <TouchableOpacity
            className="bg-red-500 px-7 py-2.5 rounded-full shadow-sm"
            activeOpacity={0.7}
          >
            <Text className="text-white font-medium">
              结算({totalQuantity})
            </Text>
          </TouchableOpacity>
        </View>
      )}
    </View>
  );
}
